import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useCommunityStore = defineStore('community', () => {
  const posts = ref([
    {
      id: 1,
      title: '我的童年记忆',
      content: '小时候在乡下奶奶家度过的夏天，总是那么难忘。那时候没有空调，只有一台老式的电风扇在房间里呼呼地转着。每天早上醒来，第一件事就是跑到院子里的井边洗脸，井水清凉甘甜，比现在的自来水要好喝多了。奶奶总是在厨房里忙碌着，为我们准备丰盛的早餐。',
      author: {
        name: '张三',
        avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      },
      type: 'memoir',
      likes: 25,
      comments: 8,
      createdAt: '2024-08-07',
      tags: ['童年', '回忆', '乡村']
    },
    {
      id: 2,
      title: '今日感悟',
      content: '今天读了一本很有意思的书《人生的智慧》，让我重新思考了人生的意义。书中提到，真正的幸福不在于拥有多少物质财富，而在于内心的平静和满足。这让我想起了小时候那些简单却快乐的日子，或许我们都应该回到那种简单的生活状态中去。',
      author: {
        name: '李四',
        avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'
      },
      type: 'diary',
      likes: 12,
      comments: 3,
      createdAt: '2024-08-06',
      tags: ['读书', '感悟', '人生']
    },
    {
      id: 3,
      title: '我的职业生涯',
      content: '从一个小城市的普通青年，到现在的企业高管，这一路走来确实不容易。记得刚毕业的时候，我怀着忐忑的心情来到大城市打拼。那时候住在一个很小的出租屋里，每天挤地铁上下班，加班到很晚是常有的事。但正是这些经历让我成长了很多，学会了独立，学会了坚持。',
      author: {
        name: '王五',
        avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
      },
      type: 'biography',
      likes: 45,
      comments: 15,
      createdAt: '2024-08-05',
      tags: ['职场', '成长', '奋斗']
    }
  ])

  const currentFilter = ref('all') // all, biography, diary, memoir
  const searchKeyword = ref('')

  const filteredPosts = computed(() => {
    let filtered = posts.value

    if (currentFilter.value !== 'all') {
      filtered = filtered.filter(post => post.type === currentFilter.value)
    }

    if (searchKeyword.value) {
      filtered = filtered.filter(post => 
        post.title.includes(searchKeyword.value) || 
        post.content.includes(searchKeyword.value) ||
        post.tags.some(tag => tag.includes(searchKeyword.value))
      )
    }

    return filtered.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
  })

  const addPost = (post) => {
    posts.value.unshift({
      id: Date.now(),
      ...post,
      likes: 0,
      comments: 0,
      createdAt: new Date().toISOString().split('T')[0]
    })
  }

  const likePost = (postId) => {
    const post = posts.value.find(p => p.id === postId)
    if (post) {
      post.likes++
    }
  }

  const setFilter = (filter) => {
    currentFilter.value = filter
  }

  const setSearchKeyword = (keyword) => {
    searchKeyword.value = keyword
  }

  return {
    posts,
    currentFilter,
    searchKeyword,
    filteredPosts,
    addPost,
    likePost,
    setFilter,
    setSearchKeyword
  }
})
